#include "StdAfx.h"

void ADTChunkRender::render() {
	if(mFirstRender) {
		initialLoad();
		mFirstRender = false;
	}

	if(mLayers == 0)
		return;

	for(ui32 i = 0; i < mLayers; ++i)
		mShader.setValue(mTextureHandles[i], mTextures[i]);

	auto alphaTex = mChunk->getAlphaTexture(); // because setValue expects IDirect3DTexture9*&
	mShader.setValue(mAlphaHandle, alphaTex);
	mShader.setValue(std::string("CameraPosition"), sCamera.GetCamPosition());
	mShader.setValue(std::string("MousePosition"), sSelection.getLastMousePos());
	mShader.setValue(std::string("matrixViewProj"), sCamera.GetMatView() * sD3D.GetMatProj());
	bool sel = true;
	mShader.setValue(std::string("DrawMouse"), sel);
	mShader.setValue("CircleRadius", sSelection.GetRadius());
	mShader.setValue("brushType", sSettings.getBrushType());

	mShader.setTechnique(mLayers - 1);

	mShader.doBasicRender(
		[this]() { mChunk->getChunkLoader().getMesh().Draw(); }
	);
}

void ADTChunkRender::initialLoad() {
	auto header = mChunk->GetHeader();
	for(auto i = 0; i < header.nLayers && i < 4; ++i) {
		mTextures[i] = sTexture.GetTexture(mChunk->GetTextureName(i));
		if(mTextures[i] == NULL)
			mTextures[i] = sTexture.GetTexture("textures\\ShaneCube.blp");

		std::stringstream param;
		param << "blendTexture" << i;
		mTextureHandles.push_back(mShader.getParamHandle(param.str()));
	}

	mLayers = header.nLayers;
	mAlphaHandle = mShader.getParamHandle("alphaTexture");
}

void ADTChunkRender::textureAdded() {
	std::stringstream param;
	param << "blendTexture" << mLayers;
	mTextureHandles.push_back(mShader.getParamHandle(param.str()));
	++mLayers;
}